import Taro, { useEffect, useState, useMemo, useDidShow, useDidHide } from '@tarojs/taro'
import _get from 'lodash/get'
import { View, Text, Input, Image } from '@tarojs/components'
import m from 'moment'
import './index.scss'

// api
import api from '../../api/index';

// utils
import getLoginInfo from "../../utils/getLoginInfo";
import getOpenId from "../../utils/getOpenId";

// global
import { REALNAME } from '../../globalData'

// hooks
import useInterval from "../../hooks/useInterval";

export default function WithDraw() {
  const [rUser, setUser] = useState()
  const [balance, setBalance] = useState(0)
  const [webToken, setWebToken] = useState('')
  const [withDraw, setWithdraw] = useState()
  const [wxOpenId, setWXOpenId] = useState('')
  const [realname, setRealname] = useState('')
  const [mobile, setMobile] = useState('')
  const [verificationCode, setVerificationCode] = useState('')
  const [countDown, setCountDown] = useState(0)
  const [delay, setDelay] = useState(null)
  const [loading, setLoading] = useState(false)
  const [isShowModal, setIsShowModal] = useState(false)
  const [errorTip, setErrorTip] = useState('')

  useDidShow(async () => {
    const user = getLoginInfo()
    if(!user) {
      return
    }
    // setWXOpenId(getOpenId())
    Taro.showLoading()
    setMobile(user.user.mobile)
    setWebToken(user.token)
    setUser(user)
    const openid = await getOpenId()
    setWXOpenId(openid)
    const realnameStorage = Taro.getStorageSync(REALNAME)
    setRealname(realnameStorage)
    getBalance()
  }, [])

  useDidHide(() => {
    setErrorTip('')
  })

  async function getBalance() {
    try {
      const data  = await api.user.getUserBalance()
      Taro.hideLoading()
      if(data.code > 0) {
        setBalance(data.data / 100)
      }
    } catch (e) {
      Taro.hideLoading()
    }
  }

  function handleInput(e) {
    setWithdraw(e.detail.value)
    // if (errorTip) {
    //   setErrorTip('')
    // }
  }

  function handleWithDrawAll() {
    setWithdraw(balance)
  }

  function handleSubmit() {

    const _withDraw = parseFloat(withDraw)

    console.log('withdraw' , _withDraw)

    if (m().hour() < 8) {
      // Taro.showToast({
      //   title: '不在提现时间段！',
      //   icon: 'none'
      // })
      setErrorTip('不在提现时间段!')
      return
    }

    if (!realname) {
      // Taro.showToast({
      //   title: '请先设置实名账号！',
      //   icon: 'none'
      // })
      setErrorTip('请先设置实名账号!')
      Taro.showModal({
        content: '请先设置实名账号',
        confirmColor: '#30c27c',
        confirmText: '去设置'
      }).then(res => {
        if (res.confirm) {
          goRealname()
        }
      })
      return
    }

    if (isNaN(_withDraw)) {
      // Taro.showToast({
      //   title: '请输入正确提现金额',
      //   icon: 'none'
      // })
      setErrorTip('请输入正确提现金额!')
      return
    } else if (_withDraw < 100){
      setErrorTip('至少提现100元!')
      return
    }

    if (withDraw > balance) {
      // Taro.showToast({
      //   title: '提现金额不能大于可提现金额!',
      //   icon: 'none'
      // })
      setErrorTip('提现金额不能大于可提现金额!')
      return
    }

    getCode()

  }

  function goRecord() {
    Taro.navigateTo({
      url: `/pages/withdrawRecord/index`
    })
  }

  function goRealname() {
    Taro.navigateTo({
      url: `/pages/realname/index`
    })
  }

  async function getCode() {
    if (errorTip) {
      setErrorTip('')
    }

    try {
      const data = await api.user.getVerification({
        mobile
      })
      if(data.code > 0) {
        setCountDown(60)
        setDelay(1000)
        setIsShowModal(true)
      } else {
        Taro.showToast({
          title: data.data,
          icon:'none'
        })
      }
    } catch (e) {
      Taro.showToast({
        title: '网络错误',
        icon: 'none'
      })
    }
  }

  useInterval(() => {
    setCountDown(countDown - 1)
    if (countDown === 1) {
      setDelay(null)
    }
  }, delay)


  async function handleWithdraw() {
    if (!verificationCode) {
      Taro.showToast({
        title: '请输入验证码'
      })
    }

    if (loading) {
      return
    }

    setLoading(true)
    const data = await api.user.postUserCashout({
      type: 2,
      wxOpenId,
      realName: realname,
      moneyInCent: withDraw * 100,
      webToken,
      mobile,
      verificationCode,
      orgId: _get(rUser, ['user', 'organization', 'org_id']) || 0,
      user_id: _get(rUser, ['user', 'user_id']),
    })
    setLoading(false)
    if(data.code < 0) {
      Taro.showToast({
        title: data.data,
        icon: 'none'
      })
    } else {
      getBalance()
      Taro.showModal({
        title: '申请成功',
        showCancel: false,
      })
      close()
      setWithdraw(0)
    }
  }

  function close() {
    setIsShowModal(false)
    setVerificationCode('')
  }

  console.log('errorTip',errorTip)

  return (
    <View className='withdraw-page'>
      <View className='can-withdraw-money-container'>
        <Text className='title'>
          可提现金额(元)
        </Text>
        <View className='num-container'>
          <Text className='sign'>￥</Text>
          {balance}
        </View>
      </View>

      <View className='withdraw-container'>
        <View className='title'>
          <View>提现金额</View>
          <View className='account' onClick={() => goRealname()}>
            {
              realname ? (
                `提现至实名账户${realname.slice(0, realname.length -1)}* >`
              ) : (
                '请设置实名账号 >'
              )
            }
          </View>
        </View>

        <View className='input-container'>
          <View className='input-wrapper'>
            <Text className='sign'>￥</Text>
            <Input
              type='number'
              className='input'
              // onChange={(e) => handleInput(e)}
              onInput={(e) => handleInput(e)}
              value={withDraw}
            />
            <Text className='all' onClick={() => handleWithDrawAll()}>全部提现</Text>
          </View>
          <View className={`errorLine ${errorTip ? 'show' : ''}`} />
        </View>

        <View className={`tips ${errorTip ? 'error' : ''}`}>
          {
            errorTip ? errorTip : '最少提现100元'
          }
        </View>

        <View className='btn' onClick={() => handleSubmit()}>
          {
            loading ? '请求中...' : '提交申请'
          }
        </View>

        <View className='record'>
          <Text onClick={() => goRecord()}>提现记录</Text>
        </View>
      </View>

      <View className='withdraw-desc-container'>
        <View className='title'>提现说明：</View>
        <View className='desc'>1 : 提交提现申请成功后，会在1-5个工作日内提现到微信零钱；</View>
        <View className='desc'>2 : 凌晨 0 : 00 ~ 8 : 00 系统维护禁止提现；</View>
        <View className='desc'>3 : 如有疑问请联系在线客服；</View>
        <View className='desc'>4 : 一旦发现任何欺诈行为，平台有权终止提现，并对您暂时或永久封号。</View>
      </View>


      <View className={`modal-container ${isShowModal ? 'show' : ''}`}>
        <View className='captcha-modal-container'>
          <View className='header'>
            短信验证
            <Image
              src={require('../../assets/cancel36X36@2x.png')}
              className='close'
              onClick={() => close()}
            />
          </View>

          <View className='content'>
            <View className='desc'>
              我们已经发送<Text className='text'>短信验证码</Text>到手机号
            </View>
            <View className='mobile'>
              {mobile}
            </View>

            <View className='form-container'>
              <Image className='cap-icon' src={require('../../assets/captcha44X44@2x.png')} />
              <Input
                className='cap-input'
                type='text'
                value={verificationCode}
                onInput={(e) => setVerificationCode(e.detail.value)}
                // onChange={(e) => setVerificationCode(e.detail.value)}
                placeholder='请输入验证码'
              />
              <Image
                className='cap-clear'
                src={require('../../assets/delete48X48@2x.png')}
                onClick={() => setVerificationCode('')}
                style={{
                  opacity: verificationCode ? 1 : 0
                }}
              />

              <View className='get-cap' onClick={() => getCode()}>
                {
                  countDown ? `${countDown}s`  : '获取验证码'
                }
              </View>
            </View>

            <View className='btn' onClick={() => handleWithdraw()}>
              {
                loading ? '请求中...' : '提 交'
              }
            </View>
          </View>
        </View>
      </View>
    </View>
  )
}

WithDraw.config = {
  navigationBarTitleText: '提现',
}
